#!/usr/bin/env python
# -*- coding: utf-8 -*-


import pandas as pd
import jieba
import re
import numpy as np
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from PIL import Image
from matplotlib import pyplot as plt
import os
from os import path

d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()

stopword = [line.rstrip() for line in open("./data/stopwords.txt", 'r', encoding='utf-8')]

newdata = []


def read_data():
    csv_data = pd.read_csv('taobao.csv', usecols=[1, 6])
    # print(csv_data)
    for i in range(len(csv_data)):
        title = csv_data['title'][i]
        newdata.append(title)
    # print(newdata)
    return newdata


def cut_word(data):
    newtext = []
    linesword = ''.join(data)
    text = re.sub(r'\d+', ' ', linesword)  # 去除数字
    text = jieba.lcut(text)  # 分词
    for word in text:
        if word not in stopword:  # 去停用词 + 词性筛选
            newtext.append(word)
    lineswords = ' '.join(newtext)
    # print(lineswords)
    return lineswords


def wordcloud(text):
    text = text.strip()
    # 设置中文字体
    # font_path = 'E:\Fonts思源黑体字体全套\SourceHanSansCN-Regular.otf'  # 思源黑体
    # font_path = 'D:\Fonts\simkai.ttf'
    font_path = 'C:\Windows\Fonts\simkai.ttf'
    # 读取背景图片
    background_Image = np.array(Image.open(path.join(d, "./data/1.jpg")))
    # 提取背景图片颜色
    img_colors = ImageColorGenerator(background_Image)
    # 设置中文停止词
    stopwords = set('')
    # stopwords.update(['但是','一个','自己','因此','没有','很多','可以','这个','虽然','因为','这样','已经','现在','一些','比如','不是','当然','可能','如果','就是','同时','比如','这些','必须','由于','而且','并且','他们'])
    wc = WordCloud(
        font_path=font_path,  # 中文需设置路径 字体设置
        margin=2,  # 页面边缘
        mask=background_Image,
        scale=2,
        max_words=200,  # 最多词个数
        min_font_size=4,  #
        stopwords=stopwords,
        random_state=42,
        background_color='white',  # 背景颜色
        # background_color='#C3481A',  # 背景颜色
        max_font_size=100,
    )
    wc.generate(text)
    # 获取文本词排序，可调整 stopwords
    process_word = WordCloud.process_text(wc, text)
    sort = sorted(process_word.items(), key=lambda e: e[1], reverse=True)
    # print(sort[:50]) # 获取文本词频最高的前50个词
    # 设置为背景色，若不想要背景图片颜色，就注释掉
    wc.recolor(color_func=img_colors)
    # 存储图像
    wc.to_file('词云1.jpg')
    # 显示图像
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.tight_layout()
    plt.show()


if __name__ == '__main__':
    data = read_data()
    text = cut_word(data)
    wordcloud(text)

